Exercise 04
Exercise 04: Checking if a Number is Negative
Your fourth task is to write a C function called my_isneg
that displays either 'N' if the integer passed as a parameter is negative, or 'P' if it is positive or null.
However, there's a twist: you can only use the my_putchar
function to output characters. The my_putchar
function takes a single character as input and outputs it.
#include <unistd.h>
void my_putchar(char c)
{
write(1, &c, 1);
}
Expected Output:
N (if the input is negative)
P (if the input is positive or zero)
Hints
Before diving into the solution, here are some hints to help you tackle the problem:
- Understand the basic conditional statements in C.
- Consider using an if-else statement to check the value of the integer.
- Use the provided
my_putchar
function to output the corresponding character.
These hints should give you a good starting point to work on the exercise. Good luck!
Solution
#include <unistd.h>
void my_putchar(char c)
{
write(1, &c, 1);
}
/*
* This function, my_isneg, displays 'N' if the integer n
* is negative, or 'P' if it is positive or zero.
* It uses the my_putchar function to output characters.
*/
int my_isneg(int n) {
if (n < 0) {
my_putchar('N');
} else {
my_putchar('P');
}
// Return 0 to indicate successful execution
return 0;
}
Explanation:
- In this solution, we use an if-else statement to check whether the integer
n
is negative. - If
n
is less than 0, we output 'N' using themy_putchar
function. - Otherwise, we output 'P' using the
my_putchar
function. - This ensures that the correct character is displayed based on the value of the integer
n
.
And voila, you've completed your fourth exercise in C programming !